import { useEffect, useState } from "react";
import {
  selectHeroesList,
  selectIsLoading,
  selectError,
  getPeople,
  selectHistory,
} from "@/entities/heroes/model/heroes";
import { useDispatch, useSelector } from "react-redux";
import { Input, Spin } from "antd";

import "./styles.sass";
import { AppDispatch } from "@/shared/typicode/heroes";
import { HeroHistory, HeroRow } from "@/entities/ui";
import { map } from "ramda";

const HeroesListPage = () => {
  //* @state
  // /** Поиск по имени */
  const [findNmae, setFindName] = useState<string>("");

  // * @selectors
  /** Список героев */
  const heroesList = useSelector(selectHeroesList);
  const isLoadind = useSelector(selectIsLoading);
  const error = useSelector(selectError);
  const historyList = useSelector(selectHistory);

  // * @actions
  const dispatch = useDispatch<AppDispatch>();

  const handleChangeFindName = (event: React.ChangeEvent<HTMLInputElement>) => {
    setFindName(event.target.value);
  };

  function PageContent() {
    if (isLoadind) return <Spin size="large" />;

    if ((heroesList !== undefined && heroesList.length === 0) || error) return <span>No heroes found</span>;

    return heroesList.map(hero => <HeroRow data={hero} />);
  }

  useEffect(() => {
    dispatch(getPeople({ search: findNmae }));
  }, [findNmae]);

  return (
    <div className="heroes-list">
      <div className="heroes-list-history">
        <span>История</span>
        {map(
          (hero: { id: string; name: string }) => (
            <HeroHistory key={hero.id} id={hero.id} name={hero.name} />
          ),
          historyList
        )}
      </div>
      <div className="heroes-list-body">
        <div className="heroes-list-body-filter">
          <Input size="large" placeholder="введите имя персонажа" onChange={handleChangeFindName} value={findNmae} />
        </div>
        <div className="heroes-list-body-all">{PageContent()}</div>
      </div>
    </div>
  );
};

export { HeroesListPage };
